import { ref, onMounted, onUnmounted, computed } from 'vue'
import { filter } from '../utils/todoStorage'
const validHash = ['all', 'active', 'completed']
export default function useFilter(todoRef) {
    const vistibilityRef = ref('all')

    const hashchange = () => {
        let hash = location.hash.replace(/#\/?/, '')
        if (validHash.includes(hash)) {
            vistibilityRef.value = hash
        } else {
            location.hash = ''
            vistibilityRef.value = 'all'
        }
    }
    // 挂载完成之后
    onMounted(() => {
        window.addEventListener('hashchange', hashchange)
    })

    // 销毁之后
    onUnmounted(() => {
        window.removeEventListener('hashchange', hashchange)
    })

    const listRef = computed(() => {
        return filter(todoRef.value, vistibilityRef.value)
    })

    const remainingRef = computed(() => {
        return filter(todoRef.value, 'active').length
    })
    return { vistibilityRef, listRef, remainingRef }
}